﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TodoApp.EntityFrameworkCore;
using TodoApp.ResultModel;
using TodoApp.TMS_SetUp.Menus;
using TodoApp.TMS_SetUp.Roles;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories.Dapper;
using Volo.Abp.EntityFrameworkCore;

namespace TodoApp.TMS_SetUp.TMS_Roles
{
    public class TMS_RoleRepository : DapperRepository<TodoAppDbContext>, ITransientDependency, ITMS_RoleRepository
    {
        public TMS_RoleRepository(IDbContextProvider<TodoAppDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="tMS_Role"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> CreateRole(TMS_Role tMS_Role)
        {
            var dbConnection = await GetDbConnectionAsync();
            return await dbConnection.ExecuteAsync($"insert into TMS_Role values(NEWID(),'{tMS_Role.Role_Name}','{tMS_Role.Role_Superior}','{tMS_Role.Role_Alias}',1,getdate())", null,
                 await GetDbTransactionAsync());
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeleteRole(string id)
        {
            var dbConnection = await GetDbConnectionAsync();
            var count = 0;
            var ids = id.Split(',');
            foreach (var item in ids)
            {
                count += await dbConnection.ExecuteAsync($"update TMS_Role set Role_Delete = 'false' where Id = '{item}'", null,
                 await GetDbTransactionAsync());
            }
            return count;
        }
        /// <summary>
        /// 显示分页
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageResponse<TMS_RoleDto>> GetRole(string name, int pageindex, int pagesize)
        {
            PageResponse<TMS_RoleDto> response = new PageResponse<TMS_RoleDto>();
            var dbConnection = await GetDbConnectionAsync();
            var sql = "select a.*,b.Role_Name as name from TMS_Role a left join TMS_Role b on a.Role_Superior=b.Id where a.Role_Delete = 'true'";
            var list = await dbConnection.QueryAsync<TMS_RoleDto>(sql, transaction: await GetDbTransactionAsync());
            response.PageTotal = list.Count();
            if (name != null)
            {
                sql += $" and a.Role_Name like '%{name}%'";
            }
            sql += $" order by a.Role_DateTime offset {(pageindex - 1) * pagesize} rows fetch next {pagesize} rows only";
            var lists = await dbConnection.QueryAsync<TMS_RoleDto>(sql, transaction: await GetDbTransactionAsync());
            response.PageData = lists.ToList();
            return response;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="tMS_Role"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdateRole(TMS_RoleDto tMS_Role)
        {
            var dbConnection = await GetDbConnectionAsync();
            return await dbConnection.ExecuteAsync($"update TMS_Role set Role_Name='{tMS_Role.Role_Name}',Role_Superior='{tMS_Role.Role_Superior}',Role_Alias='{tMS_Role.Role_Alias}' where Id = '{tMS_Role.Id}'", null,
                 await GetDbTransactionAsync());
        }
        /// <summary>
        /// 菜单显示
        /// </summar 8y>
        /// <param name="response"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<TMS_Menus>> GetMenu()
        {
            var dbConnection = await GetDbConnectionAsync();
            var list = (await dbConnection.QueryAsync<TMS_Menus>("select * from TMS_Menu", transaction: await GetDbTransactionAsync())).ToList();
            return GetViewModels(list);
        }
        public List<TMS_Menus> GetViewModels(List<TMS_Menus> list, string Menu_Superior = "M0")
        {
            var dbConnection = GetDbConnectionAsync();
            return list.Where(p => p.Menu_Superior == Menu_Superior).Select(t => new TMS_Menus
            {
                Menu_Superior = Menu_Superior,
                Menu_Id = t.Menu_Id,
                Menu_Name = t.Menu_Name,
                Children = GetViewModels(list, t.Menu_Id)
            }).ToList();
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="name"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResponseModel<bool>> CreateMenu(string name, string ids)
        {
            ResponseModel<bool> response = new ResponseModel<bool>();
            var dbConnection = await GetDbConnectionAsync();
            var count = 0;
            var list = (await dbConnection.QueryAsync<TMS_Menus>($"select * from TMS_Menu where Role_Id = '{name}'", transaction: await GetDbTransactionAsync())).ToList();
            if (list != null)
            {
                var sql = $"delete TMS_RoleMenu where Role_Id = '{name}'";
                await dbConnection.ExecuteAsync(sql, null,await GetDbTransactionAsync());
            }
            dbConnection.Open();
            using (var begin = dbConnection.BeginTransaction())
            {
                try
                {
                    if (ids != null)
                    {
                        var id = ids.Split(',');
                        foreach (var item in id)
                        {
                            var sql = $"insert into TMS_RoleMenu values('{name}','{item}')";
                            count += await dbConnection.ExecuteAsync(sql, null,begin);
                        }
                    }
                    if (count > 1)
                    {
                        begin.Commit();
                        return response.Succeed(true);
                    }
                    else
                    {
                        begin.Rollback();
                        return response.Succeed(false);
                    }

                }
                catch (Exception)
                {

                    throw;
                }
            }
        }
    }
}
